import socket
import time

import pymysql
import threading
from datetime import datetime

# TCP服务器配置
host = '192.168.0.168'  # 监听所有接口
port = 65535     # 监听的端口

# MySQL数据库配置
mysql_host = 'localhost'
mysql_user = 'root'
mysql_password = '123456'
mysql_db = 'iot_local'


def client_handler(client_socket, client_address):
    # 连接到MySQL数据库
    try:
        mysql_conn = pymysql.connect(host=mysql_host, user=mysql_user, password=mysql_password, db=mysql_db)
        mysql_cursor = mysql_conn.cursor()
        while True:
            # 接收数据
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                break  # 如果没有数据，跳出循环
            # 解析数据
            data_lines = data.strip().split(';')
            for line in data_lines:
                if line:
                    parts = line.split(',')
                    if len(parts) == 4:  # Ensure there are 4 parts to unpack
                        grp, dev, type_, num = parts
                        grp, dev, type_, num = grp.split(':')[1], dev.split(':')[1], type_.split(':')[1], \
                        num.split(':')[1]
                        # Now you can process each part as needed
                    else:
                        print(f"Skipping invalid line: {line}")
                        continue
                    receive_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')



                    # 写入MySQL数据库
                    sql = "INSERT INTO iotdemo (grp, dev, type, num, receive_time) VALUES (%s, %s, %s, %s, %s)"
                    mysql_cursor.execute(sql, (grp, dev, type_, num, receive_time))
                    mysql_conn.commit()


            # 处理数据...
            # 例如，您可以在这里解析数据并将其存储到数据库中

    except Exception as e:
        print(f"Error handling client {client_address}: {type(e).__name__}: {e}")
        mysql_cursor.close()
        mysql_conn.close()
    finally:
        # 关闭客户端连接
        client_socket.close()
        print(f"Connection with {client_address} closed")

# try:
#     while True:
#         # 等待客户端连接
#         client_socket, addr = server_socket.accept()
#         print(f"New connection from {addr}")
#         client_thread = threading.Thread(target=client_handler, args=(client_socket, addr))
#         time.sleep(10)
#         client_thread.start()
# except KeyboardInterrupt:
#     print("TCP Server stopped by keyboard interrupt")
# finally:
# # 关闭服务器套接字
#     server_socket.close()


def start_server():
    # 创建TCP服务器套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(16)
    print(f"TCP Server listening on {host}:{port}")


    try:
        while True:
            # 等待客户端连接
            client_socket, addr = server_socket.accept()
            print(f"New connection from {addr}")
            client_thread = threading.Thread(target=client_handler, args=(client_socket, addr))
            client_thread.start()
    except Exception as e:
        print(f"Server error: {type(e).__name__}: {e}")
        time.sleep(5)  # 暂停5秒
        start_server()  # 重启服务器
    finally:
        # 关闭服务器套接字
        server_socket.close()


if __name__ == "__main__":
    try:
        start_server()
    except KeyboardInterrupt:
        print("TCP Server stopped by keyboard interrupt")

